package com.xishu.foodpanda;

import com.alibaba.fastjson.JSONObject;
import com.xishu.client.HttpClientUtil;
import com.xishu.entity.shop.FoodPandaConfig;
import com.xishu.entity.shop.Shop;
import com.xishu.exception.ResponseStatusException;
import com.xishu.response.VerifyUtil;
import com.xishu.util.AES;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class FoodPandaClient {
    public static final String END_POINT = "https://integration-middleware.as.restaurant-partners.com";
    public static final String LOGIN = "/v2/login";

    private static Logger logger = LoggerFactory.getLogger(FoodPandaClient.class);

    private static FoodPandaClient instance = new FoodPandaClient();

    private FoodPandaClient() {
    }

    public static FoodPandaClient getInstance() {
        return instance;
    }

    /**
     * 登录
     *
     * @param shop
     * @return
     */
    public String login(Shop shop) throws ResponseStatusException {
        VerifyUtil.verify(() -> shop != null);
        VerifyUtil.verify(() -> shop.getId() != null);
        VerifyUtil.verify(() -> shop.getFoodPandaConfig() != null);
        FoodPandaConfig foodPandaConfig = shop.getFoodPandaConfig();
        logger.info("shop {} begin to login", shop.getId());

        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("username", foodPandaConfig.getUsername());
        dataMap.put("password", AES.decrypt(foodPandaConfig.getPassword()));
        dataMap.put("grant_type", "client_credentials");

        return HttpClientUtil.post(END_POINT + LOGIN, null, dataMap);
    }

    /**
     * 向foodpanda发送命令
     *
     * @param uri     哪一个URI
     * @param dataMap
     * @param token
     */
    public void sendCmd(String uri, Map<String, Object> dataMap, String token) {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + token);
        String data = JSONObject.toJSONString(dataMap);
        HttpClientUtil.jsonPut(END_POINT + uri, headerMap, data);
    }

    /**
     * 获取日志
     *
     * @param uri
     * @param dataMap
     * @param token
     */
    public String getLog(String uri, Map<String, String> dataMap, String token) throws URISyntaxException {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + token);
        return HttpClientUtil.jsonGet(END_POINT + uri, headerMap, dataMap);
    }
}
